import { defineStore } from 'pinia';
import { ref } from 'vue';
import { computed } from 'vue'
import { useUserStore } from './user';
import { insertCartAPI, findNewCartListAPI, delCartAPI } from '@/apis/cart';


export const useCartStore = defineStore('cart', () => {
    const cartlist = ref([])
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)
    //获取最新购物车
    const updateCartList = async () => {
        const res = await findNewCartListAPI()
        cartlist.value = res.result
    }


    // 添加商品到购物车
    const addCart = async (goods) => {
        const { skuId, count } = goods
        if (isLogin.value) {
            await insertCartAPI({ skuId, count })
            updateCartList()
        } else {
            const item = cartlist.value.find((item) => goods.skuId === item.skuId)
            if (item) {
                item.count += goods.count
            } else {
                cartlist.value.push(goods)
            }
        }

    }
    //删除商品
    const delCart = async (skuId) => {
        if (isLogin.value) {
            await delCartAPI([skuId])
            updateCartList()
        } else {
            const idx = cartlist.value.findIndex((item) => skuId === item.skuId)
            cartlist.value.splice(idx, 1)
        }

    }
    //清楚购物车
    const clearCartList = () => {
        cartlist.value = []
    }

    //单选商品
    const singleCheck = (skuId, selected) => {
        const item = cartlist.value.find((item) => item.skuId === skuId)
        item.selected = selected
    }

    //全选商品
    const allCheck = (selected) => {
        cartlist.value.forEach(item => item.selected = selected)
    }

    //计算属性
    //1、总数
    const allCount = computed(() => cartlist.value.reduce((a, b) => a + b.count, 0))
    //2、总价
    const allPrice = computed(() => cartlist.value.reduce((a, b) => a + b.price * b.count, 0))
    //3、已选择商品数量
    const selectedCount = computed(() => cartlist.value.filter(item => item.selected).reduce((a, b) => a + b.count, 0))
    //4、已选商品总价
    const selectedPrice = computed(() => cartlist.value.filter(item => item.selected).reduce((a, b) => a + b.price * b.count, 0))
    //是否全选
    const isAll = computed(() => cartlist.value.every((item) => item.selected))

    return {
        cartlist,
        allCount,
        allPrice,
        isAll,
        selectedCount,
        selectedPrice,
        clearCartList,
        addCart,
        delCart,
        singleCheck,
        allCheck,
        updateCartList
    }
}, {
    persist: true
}
)